package com.donfelix.looknews.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.donfelix.looknews.R;

import java.util.List;

/**
 * Created by Don on 2017/3/31.
 * Desc
 */

public class AutoScrollViewPager extends ViewPager {

    private final int MESSAGE_WHAT = 0;
    private final int AUTO_SCROLL_DELAY = 3000;
    private List<String> imageUrls;
    private List<String> titles;
    private TextView title;
    private List<ImageView> dots;
    private ImageView dotFocus;
    private AutoAdapter adapter;
    private int previousPosition;
    private long downTime;
    private int mStartX;
    private int mStartY;
    private OnItemClickListener itemClickListener;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_WHAT:
                    int currentItem = AutoScrollViewPager.this.getCurrentItem();
                    int position = (currentItem + 1) % (imageUrls.size());
                    AutoScrollViewPager.this.setCurrentItem(position, true);
                    sendEmptyMessageDelayed(MESSAGE_WHAT, AUTO_SCROLL_DELAY);
                    break;
                default:
                    break;
            }
        }
    };

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public AutoScrollViewPager(Context context) {
        this(context, null);
    }

    public AutoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                title.setText(titles.get(position));
                dots.get(previousPosition).setImageResource(R.drawable.dot_normal);
                previousPosition = position;
                dots.get(position).setImageResource(R.drawable.dot_focused);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                dotFocus.setVisibility(View.GONE);
            }
        });

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下的时候，取消自动轮播
                        handler.removeCallbacksAndMessages(null);
                        downTime = System.currentTimeMillis();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        handler.sendEmptyMessageDelayed(MESSAGE_WHAT, AUTO_SCROLL_DELAY);
                        break;
                    case MotionEvent.ACTION_UP:
                        handler.sendEmptyMessageDelayed(MESSAGE_WHAT, AUTO_SCROLL_DELAY);
                        long upTime = System.currentTimeMillis();
                        if ((upTime - downTime) < 500) {//如果按下和抬起之间的时间间隔小于500毫秒，我们认为是点击事件
                            if (itemClickListener != null) {
                                int position = AutoScrollViewPager.this.getCurrentItem();
                                itemClickListener.onItemClick(position);
                            }
                        }
                        break;
                }
                return false;//事件不拦截
            }
        });
    }

    public void setImageUrls(List<String> imageUrls) {
        this.imageUrls = imageUrls;
    }

    public void setDots(List<ImageView> dots, ImageView dotFocus) {
        this.dots = dots;
        this.dotFocus = dotFocus;
    }

    public void setTitles(List<String> titles, TextView title) {
        this.titles = titles;
        this.title = title;
    }

    public void start() {
        if (adapter == null) {
            adapter = new AutoAdapter();
            this.setAdapter(adapter);
        } else {
            this.adapter.notifyDataSetChanged();
        }
        title.setText(titles.get(0));
        handler.sendEmptyMessageDelayed(MESSAGE_WHAT, AUTO_SCROLL_DELAY);
    }

    private class AutoAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return imageUrls.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = new ImageView(container.getContext());
            Glide.with(container.getContext()).load(imageUrls.get(position))
                    .centerCrop().into(imageView);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) ev.getX();
                mStartY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                int currentX = (int) ev.getX();
                int currentY = (int) ev.getY();
                if (Math.abs(currentX - mStartX) < Math.abs(currentY - mStartY)) {//横向没有纵向滑的多，认为是上下滑动
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {//左右滑动
                    getParent().requestDisallowInterceptTouchEvent(true);//请求父控件不拦截
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }
}
